package db

import (
	"fmt"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

// 全局数据库连接
var Db *sqlx.DB

// 数据库连接配置
const (
	DBHost     = "47.100.111.28:4861"
	DBUser     = "root"
	DBPassword = "4861abc165"
	DBName     = "blogv2"
)

// InitDB 初始化数据库连接
func InitDB() error {
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Asia%%2FShanghai",
		DBUser, DBPassword, DBHost, DBName)

	var err error
	Db, err = sqlx.Connect("mysql", dsn)
	if err != nil {
		return fmt.Errorf("连接数据库失败: %v", err)
	}

	// 测试数据库连接
	if err = Db.Ping(); err != nil {
		return fmt.Errorf("数据库连接测试失败: %v", err)
	}

	// 设置连接池参数
	Db.SetMaxOpenConns(100)
	Db.SetMaxIdleConns(10)
	Db.SetConnMaxLifetime(time.Hour)

	return nil
}
